package com.dy.video.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("video")
public class EsController {
    @RequestMapping("/search")
    public List<Map<String, Object>> search1(@RequestParam("uname") String uname) throws IOException {
        // 创建Java和ES的链接
        HttpHost httpHost = new HttpHost("127.0.0.1", 9200, "http");
        RestClientBuilder builder = RestClient.builder(httpHost);
        RestHighLevelClient client = new RestHighLevelClient(builder);
        // 编写查询操作
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("video");
        // 构建查询条件
        SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchQuery("uname", uname));
        // 设置高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("uname");
        query.highlighter(highlightBuilder);
        // 建立查询条件的关系blanchedalmond
        searchRequest.source(query);
        // 发送请求
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        // 展示响应结果
        SearchHits hits = response.getHits();
        List<Map<String, Object>> results = new ArrayList<>();
        for (SearchHit hit : hits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            // 添加高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields.containsKey("name")) {
                HighlightField highlightField = highlightFields.get("name");
                sourceAsMap.put("highlightedName", highlightField.fragments()[0].toString());
            }
            results.add(sourceAsMap);
        }
        // 关闭连接
        client.close();

        System.out.println("123456:" + results);
        return results;
    }
}
